<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="类别名称" v-bind="validateInfos.pid">
            <!-- <JTreeSelect v-model:value="formData.pid" :async="false" pidField="pid" dict="lab_items,name,id"
              :disabled="disabled" /> -->              
              <a-input v-model:value="formData.largeCategory" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="项目名称" v-bind="validateInfos.name">
            <a-input v-model:value="formData.name" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="所属部门" v-bind="validateInfos.team">
            <a-input v-model:value="formData.team" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <!-- 设备选择 -->
    <BasicTable @register="registerTable" :dataSource="formData.itemsDeviceList" :pagination="false" :disable="disabled" style="height: 100%">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined">选择设备</a-button>
      </template>
      <!--操作栏-->
      <template #action="{ index, record }">
        <TableAction :actions="getTableAction(index, record)" />
      </template>
    </BasicTable>
  </a-spin>
  <TableDevModal @register="registerDevModal" @getSelectResult="onSelectOk"></TableDevModal>
</template>
<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed } from 'vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { useModal } from '/@/components/Modal';
import { BasicTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage';
import {deviceQueryList} from '../LabItems.api';
import { getValueType } from '/@/utils';
import { saveOrUpdate } from '../LabItems.api';
import { Form } from 'ant-design-vue';
import TableDevModal from '/@/views/lab/items_check/subTables/LabDevAndUteList.vue';

const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => { } },
  formBpm: { type: Boolean, default: true },
});
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  team: '',
  name: '',
  basisName: '',
  basisNum: '',
  scope: '',
  itemNorm: '',
  normType: '',
  remark: '',
  basisAtta: '',
  type: 'C',
  pid: '',
  level: '3',
  depart: '',
  itemsDeviceList: [],
  largeCategory:'',
});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = {};
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });

// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});
const columnsBasic: any = [
  {
    title: '设备名称',
    align: 'left',
    dataIndex: 'devName',
    key: 'devName',
  },
  {
    title: '规格型号',
    align: 'center',
    dataIndex: 'devModel',
  },
  {
    title: '设备自编号',
    align: 'center',
    dataIndex: 'devNumber',
  },
];
const { tableContext } = useListPage({
  tableProps: {
    title: '实验设备',
    columns: columnsBasic,
    canResize: false,
    useSearchForm: false,
    showIndexColumn: true,
    actionColumn: {
      width: 150,
      fixed: 'right',
    },
  },
});
const [registerTable,{reload}] = tableContext;

const [registerDevModal, { openModal }] = useModal();

/**
 * 新增
 */
function add(largeCategory) {
  edit(largeCategory,{});
}

/**
 * 编辑
 */
async function edit(largeCategory,record) {
  const itemsDeviceList = []
  if(record && record.id){
    const params = {id:record.id}
    const res = await deviceQueryList(params);
    Object.assign(itemsDeviceList,res.result.itemsDeviceList);
  }
  nextTick(() => {
    resetFields();
    //赋值
    formData.itemsDeviceList = itemsDeviceList
    formData.largeCategory=largeCategory.name;
    formData.pid = largeCategory.id;
    Object.assign(formData, record);
    reload();
  });
}

/**
 * 提交数据
 */
async function submitForm() {
  // 触发表单验证
  await validate();
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  // for (let data in model) {
  //   //如果该数据是数组并且是字符串类型
  //   if (model[data] instanceof Array) {
  //     let valueType = getValueType(formRef.value.getProps, data);
  //     //如果是字符串类型的需要变成以逗号分割的字符串
  //     if (valueType === 'string') {
  //       model[data] = model[data].join(',');
  //     }
  //   }
  // }
  await saveOrUpdate(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}
const handleAdd = () => {
  openModal(true);
}
/**
* 操作栏
*/
function getTableAction(index, record) {
  return [
    {
      label: '删除',
      color: 'error',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(index, record),
      },
    },
  ];
}
function handleDelete(index) {
  formData.itemsDeviceList.splice(index, 1);
}
function onSelectOk(devList) {
  if (devList.length > 0) {
    formData.itemsDeviceList.splice(0, formData.itemsDeviceList.length);
    // labRecordDevList.value.splice(0, labRecordDevList.value.length);
    devList.forEach(item => {
      formData.itemsDeviceList.push({
        id: "",
        taskId: "",
        itemId: "",
        devId: item.devId,
        devName: item.devName,
        devModel:item.devModel,
        devNumber: item.devNum,
        devValidity: item.devValidity,
      })
    });
  } else {
    if (formData.itemsDeviceList.length <= 0) {
      formData.itemsDeviceList.push({
        id: "",
        taskId: "",
        itemId: "",
        devId: "",
        devName: "",
        devModel:"",
        devNumber: "",
        devValidity: "",
      })
    }
  }
  reload();
}
defineExpose({
  add,
  edit,
  submitForm,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  // min-height: 500px !important;
  overflow-y: auto;
  padding: 24px 24px 24px 24px;
}
</style>
